package com.semeureka.frame.util;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoService;
import org.apache.mina.core.service.IoServiceListener;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class SmsServer {
	private IoConnector connector;
	private IoSession session;

	public void setConnector(IoConnector connector) {
		this.connector = connector;
		this.connector.addListener(new IoServiceListenerImpl());
	}

	public void sendSms(Sms sms) {
		if (session != null && !session.isClosing()) {
			String response = writeAndResponse("AT\r");
		}
	}

	private String writeAndResponse(String request) {
		session.write(IoBuffer.wrap(request.getBytes()));
		return request;
	}

	private final class IoServiceListenerImpl implements IoServiceListener {
		@Override
		public void sessionCreated(IoSession session) throws Exception {
			SmsServer.this.session = session;
		}

		@Override
		public void sessionDestroyed(IoSession session) throws Exception {
			// Do nothing
		}

		@Override
		public void serviceIdle(IoService service, IdleStatus idleStatus) throws Exception {
			// Do nothing
		}

		@Override
		public void serviceDeactivated(IoService service) throws Exception {
			// Do nothing
		}

		@Override
		public void serviceActivated(IoService service) throws Exception {
			// Do nothing
		}
	}
}
